var root = "/app/v1/";
//var root = "http://192.168.1.115:8603/app/v1/"
//var root = "http://120.79.138.124:9090/app/v1/"
//var root = "http://app.uuclass.cn:9090/app/v1/"
import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import {
    MessageBox
} from 'mint-ui';
import {
    Indicator
} from 'mint-ui';
/**
说明：
import list from './list';//ES6格式
//等价于
var list = require('./list'); //commonjs格式:经典的commonjs同步语法
**/

var Golbale = new Vue();

function BackTop(domE, distance) {
    var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
    if (currentScroll > 0) {
        window.requestAnimationFrame(BackTop);
        window.scrollTo(0, currentScroll - (currentScroll / 5));
    }
};
// 自定义判断元素类型JS
function toType(obj) {
    return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 参数过滤函数
function filterNull(o) {
    for (var key in o) {
        if (o[key] === null) {
            delete o[key]
        }
        if (toType(o[key]) === 'string') {
            o[key] = o[key].trim();
            o[key] = utf16toEntities(o[key]); //参数如果含有utf16emoji表情,就转化为字符串存储
        } else if (toType(o[key]) === 'object') {
            o[key] = filterNull(o[key])
        } else if (toType(o[key]) === 'array') {
            o[key] = filterNull(o[key])
        }
    }
    return o
}
/*
  接口处理函数
  这个函数每个项目都是不一样的，我现在调整的是适用于
  https://cnodejs.org/api/v1 的接口，如果是其他接口
  需要根据接口的参数进行调整。参考说明文档地址：
  https://cnodejs.org/topic/5378720ed6e2d16149fa16bd
  主要是，不同的接口的成功标识和失败提示是不一致的。
  另外，不同的项目的处理方法也是不一致的，这里出错就是简单的alert
*/

function apiAxios(method, url, params, success, failure, isImg) {
    if (params) {
        params = filterNull(params)
    }
    let config = {
        method: method,
        url: url,
        data: method === 'POST' || method === 'PUT' ? qs.stringify(params) : null,
        params: method === 'GET' || method === 'DELETE' ? params : null,
        baseURL: root,
        timeout: 30000
    }
    if (isImg) {
        let formData = new FormData();
        for (var i in params) {
            formData.append(i, params[i])

        }
        formData.append('filename', 'file');
        config.headers = {
            'Content-Type': 'multipart/form-data'
        }
        config.data = formData;
        console.log('123', config);
    }
    Indicator.open({
        text: '加载中...',
        spinnerType: 'fading-circle'
    });
    axios(config)
        .then(function(res) {
            Indicator.close();
            if (res.data.success === true) {
                console.log(3)
                if (success) {
                    success(res.data)
                }
            } else {
                if (failure) {
                    failure(res.data)
                } else {
                    console.log(2)
                    MessageBox('提示', res.data.retCodeEnCn);
                }
            }
        })
        .catch(function(err) {
            Indicator.close();
            console.log(1)
            let res = err.response
            if (err) {
                if (res) {
                    window.alert('api error, HTTP CODE: ' + res.status)
                }
            }
        })
}

function getPushInfo() { //获取推送信息
    var info = plus.push.getClientInfo();
    console.log("获取客户端推送标识信息：");
    console.log("token: " + info.token);
    console.log("clientid: ", info.clientid);
    console.log("appid: " + info.appid);
    console.log("appkey: " + info.appkey);
}

function getImage(success, failure) { // 拍照
    if (!window.plus) {
        MessageBox('提示', '当前设备不支持拍照！');
        return false;
    }
    console.log('开始拍照：');
    var cmr = plus.camera.getCamera();
    cmr.captureImage(function(p) {
        console.log('成功:' + p);
        plus.io.resolveLocalFileSystemURL(p, function(entry) {
            success(p, entry.toLocalURL());
        }, function(e) {
            failure(entry);
            console.log('读取拍照文件错误：' + e.message);
        });
    }, function(e) {
        console.log('失败：' + e.message);
    }, {
        filename: '_doc/camera/',
        index: 1
    });
}

function createUpload(url, params, success) { //上传图片  

    var task = plus.uploader.createUpload("http://180.76.51.106:8080/tms" + url, {
            method: "POST",
            blocksize: 204800,
            priority: 100
        },
        function(t, status) {
            // 上传完成  
            if (status == 200) {
                console.log('提交成功')
                success(t);
            } else {
                console.log("Upload failed: " + status);
            }
        }
    );
    task.addFile(params.file, {
        key: "file"
    });
    task.addData("dispatch_no", params.dispatch_no);
    task.addData("source_unique_no", params.source_unique_no);
    //task.addEventListener( "statechanged", onStateChanged, false );  
    task.start();
}

function tell(number) { //打电话
    window.location.href = "tel:" + number;
}

function formatDate(now) {
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var date = now.getDate();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    return year + "-" + month + "-" + date
}

function formatTime(now) {
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    return hour + ":" + minute;
}
Date.prototype.Format = function(fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function removeCookie(cookie) {
    if (cookie) {
        sessionStorage.removeItem(cookie);
    } else { //全部移除
        sessionStorage.removeItem('base64');
        sessionStorage.removeItem('selectStudentList');
        sessionStorage.removeItem('detail');
        sessionStorage.removeItem('studentType');
        sessionStorage.removeItem('radioBackOptions');
    }
}

function formatterImg(imgSrc) {
    if (!imgSrc) {
        return '/dist/static/images/gzt/02@2x.png';
    }
    if (imgSrc.indexOf('.png') != -1) {
        imgSrc = imgSrc.replace('.png', '_100x100.png')
    } else if (imgSrc.indexOf('.jpg') != -1) {
        imgSrc = imgSrc.replace('.jpg', '_100x100.jpg')
    }
    return imgSrc;
}

function showImgDetail(imgSrc) {
    if (imgSrc) {
        Golbale.$emit('showImgPopup', imgSrc);
    } else {
        return false;
    }
}

function goBack() {
    window.history.go(-1);
}
// 返回在vue模板中的调用接口
function clearItem(item, item2) { //清除除登录信息以及传进来的item以外的所有cookie
    var useInfo = JSON.parse(sessionStorage.getItem('useInfo'));
    let noRemoveItem = JSON.parse(sessionStorage.getItem(item));
    let noRemoveItem2 = JSON.parse(sessionStorage.getItem(item2));
    sessionStorage.clear();
    if (noRemoveItem) {
        sessionStorage.setItem(item, JSON.stringify(noRemoveItem));
    }
    if (noRemoveItem2) {
        sessionStorage.setItem(item2, JSON.stringify(noRemoveItem2));
    }
    sessionStorage.setItem('useInfo', JSON.stringify(useInfo));
}
var pays = {};
//支付相关
function getChanels() {
    plus.payment.getChannels(function(channels) {
        for (var i in channels) {
            var channel = channels[i];
            if (channel.id == 'qhpay' || channel.id == 'qihoo') { // 过滤掉不支持的支付通道：暂不支持360相关支付
                continue;
            }
            pays[channel.id] = channel;
            checkServices(channel);
        }
    }, function(e) {
        console.log('获取支付通道失败：' + e.message);
    });
}

function clickModel(index) { //暂时不需要点击事件,防范于未然
    // console.log('点击model');
    // MessageBox('提示', '没有编辑权限');
}

function updata() {
    var url = 'version/getNewVersion'
    apiAxios('POST', url, {}, data => {
        console.log("最新版本:" + data.info.mark)
            // 获取本地应用资源版本号
        plus.runtime.getProperty(plus.runtime.appid, inf => {                     
            console.log("当前应用版本：" + inf.version);  
            if (data.info.mark != inf.version) {
                MessageBox.confirm('有新版本是否立即更新?').then(o => {
                    var wgturl = data.info.url
                    var wt = plus.nativeUI.showWaiting('下载更新中，请勿关闭');
                    var dtask = plus.downloader.createDownload(wgturl, {}, function(d, status) {
                        if (status == 200) {
                            var path = d.filename;
                            wt.setTitle("下载完成,资源解压中,请勿关闭,该过程不消耗流量!");
                            plus.runtime.install(path, {}, o => {
                                wt.setTitle("更新成功,将重启");
                                wt.close();
                                plus.runtime.quit();
                            });
                        } else { //下载失败
                            alert('Download failed:' + status);
                        }
                    });
                    dtask.addEventListener("statechanged", function(task, status) {
                        switch (task.state) {
                            case 3:
                                var a = task.downloadedSize / task.totalSize * 100;
                                wt.setTitle(" 已下载" + parseInt(a) + "% ");
                                break;
                        }
                    });
                    dtask.start();
                }).catch(e => {

                })
            }                         
            // if (plus.os.name == "iOS") { // 检测app小版本的更新,IOS不检查大版本
            //     upgrade.checkForWgt(wgtVer, null, page.init) 
            // } else if (plus.os.name == "Android") {  // 先检测大版本的更新，如果没有再检测app小版本的更新
            //     upgrade.checkForApp({ appVersion: app.currVersion, wgtVersion: wgtVer }, null, page.init);                    
            // }            
        });

    })

}

function payMoney(order, Type, callback) { //这里需要调用支付宝或微信的支付接口
    var payId = '';
    switch (Type) {
        case 1: //微信支付
            payId = 'wxpay'
            break;
        case 2: //支付宝支付
            payId = 'alipay'
            break;
    }
    plus.payment.request(pays[payId], order, function(result) {
        console.log('result' + JSON.stringify(result))
        let url = 'payLog/onReturn'
        var params = {
            resultJson: JSON.stringify(result)
        }
        apiAxios('POST', url, params, (data) => { //获取msg
            console.log('result' + JSON.parse(JSON.stringify(data)));
            MessageBox('提示', '支付成功');
            callback(result);
        })

    }, function(e) {
        MessageBox('操作失败', e.message);
    });
}

function checkServices(pc) {
    if (!pc.serviceReady) {
        var txt = null;
        switch (pc.id) {
            case 'alipay':
                txt = '检测到系统未安装“支付宝快捷支付服务”，无法完成支付操作，是否立即安装？';
                break;
            default:
                txt = '系统未安装“' + pc.description + '”服务，无法完成支付，是否立即安装？';
                break;
        }
        plus.nativeUI.confirm(txt, function(e) {
            if (e.index == 0) {
                pc.installService();
            }
        }, pc.description);
    }
}

var w = null;

function pay(id, callback) {
    if (w) {
        return;
    } //检查是否请求订单中
    console.log('----- 请求支付 -----');
    if (id == 'alipay' || id == 'wxpay') {
        url += 'payid=' + id;
    } else {
        plus.nativeUI.alert('当前环境不支持此支付通道！');
        return;
    }
    var appid = plus.runtime.appid;
    // if (navigator.userAgent.indexOf('StreamApp') >= 0) {
    //     appid = 'Stream';
    // }
    url += '&appid=' + appid;

    w = plus.nativeUI.showWaiting();
    // 请求支付订单
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        switch (xhr.readyState) {
            case 4:
                w.close();
                w = null;
                if (xhr.status == 200) {
                    console.log('----- 请求订单成功 -----');
                    console.log(xhr.responseText);
                    var order = xhr.responseText;
                    plus.payment.request(pays[id], order, function(result) {
                        MessageBox('提示', '支付成功');
                        callback();

                    }, function(e) {
                        MessageBox('操作失败', e.message);
                    });
                } else {
                    console.log('----- 请求订单失败 -----');
                    console.log(xhr.status);
                    plus.nativeUI.alert('获取订单信息失败！', null, '捐赠');
                }
                break;
            default:
                break;
        }
    }
    xhr.open('GET', url);
    console.log('请求支付订单：' + url);
    xhr.send();
}
//分享相关
function plusReady() {
    updateSerivces(); //获取分享通道
    getChanels(); //获取支付通道
    getPushInfo(); //获取推送信息
    plus.navigator.setStatusBarBackground("#0489ff"); //顶部状态栏背景色
}
if (window.plus) { //当plusReady时,获取分享列表,目前只有微信分享,
    plusReady();
} else {
    document.addEventListener('plusready', plusReady, false);
}
var shares = null;

function updateSerivces() { //获取分享列表
    plus.share.getServices(function(s) {
        shares = {};
        for (var i in s) {
            var t = s[i];
            shares[t.id] = t;
        }
    }, function(e) {
        console.log('获取分享服务列表失败：' + e.message);
    });
}

function shareHref(msg) { //分享链接
    var shareBts = [];
    // 更新分享列表
    var ss = shares['weixin'];
    ss && ss.nativeClient && (shareBts.push({
            title: '微信朋友圈',
            s: ss,
            x: 'WXSceneTimeline'
        }),
        shareBts.push({
            title: '微信好友',
            s: ss,
            x: 'WXSceneSession'
        }));
    ss = shares['qq'];
    ss && ss.nativeClient && shareBts.push({
        title: 'QQ',
        s: ss
    });
    // 弹出分享列表
    shareBts.length > 0 ? plus.nativeUI.actionSheet({
        title: '分享链接',
        cancel: '取消',
        buttons: shareBts
    }, function(e) {
        (e.index > 0) && shareAction(shareBts[e.index - 1], true, msg);
    }) : plus.nativeUI.alert('当前环境无法支持分享链接操作!');
}

function shareAction(sb, bh, msg) {
    console.log('分享操作：');
    if (!sb || !sb.s) {
        console.log('无效的分享服务！');
        return;
    }
    msg.extra = {
        scene: sb.x,
    }


    if (sb.s.authenticated) {
        console.log('---已授权---');
        shareMessage(msg, sb.s);
    } else {
        console.log('---未授权---');
        sb.s.authorize(function() {
            shareMessage(msg, sb.s);
        }, function(e) {
            console.log('认证授权失败：' + e.code + ' - ' + e.message);
        });
    }
}

function utf16toEntities(str) { //检测utf16emoji表情 转换为实体字符以供后台存储
    var patt = /[\ud800-\udbff][\udc00-\udfff]/g;
    str = str.replace(patt, function(char) {
        var H, L, code;
        if (char.length === 2) { //辅助平面字符（我们需要做处理的一类）
            H = char.charCodeAt(0); // 取出高位
            L = char.charCodeAt(1); // 取出低位
            code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法
            return "&#" + code + ";";
        } else {
            return char;
        }
    });
    return str;
}

function shareMessage(msg, s) {
    console.log(JSON.stringify(msg));
    console.log('s' + JSON.stringify(s))
    s.send(msg, function() {
        console.log('分享到"' + s.description + '"成功！');
        Indicator.close();
    }, function(e) {
        console.log('分享到"' + s.description + '"失败: ' + JSON.stringify(e));
        Indicator.close();
    });
    Indicator.open({
        text: '加载中...',
    });
}

function shareImgContent(title, content, pictures) {
    var shareBts = [];
    // 更新分享列表
    var ss = shares['weixin'];
    ss && ss.nativeClient && (shareBts.push({
            title: '微信朋友圈',
            s: ss,
            x: 'WXSceneTimeline'
        }),
        shareBts.push({
            title: '微信好友',
            s: ss,
            x: 'WXSceneSession'
        }));
    // ss = shares['qq'];
    // ss && ss.nativeClient && shareBts.push({
    //     title: 'QQ',
    //     s: ss
    // });
    var msg = {
        content,
        title,
        pictures,
    };
    // msg.thumbs = ['_www/logo.png'];
    // msg.pictures = ['_www/logo.png'];

    shareBts.length > 0 ? plus.nativeUI.actionSheet({
        title: '分享图文',
        cancel: '取消',
        buttons: shareBts
    }, function(e) {
        (e.index > 0) && shareAction(shareBts[e.index - 1], true, msg);
    }) : plus.nativeUI.alert('当前环境无法支持分享链接操作!');
}

function share(item) {


    var msg = { //先假装拿到msg了
        title: "哈哈哈",
        content: '我胡汉三又回来了',
        href: 'www.baidu.com',
    }
    let content = item.title;
    let pictures = item.filePathList.map(o => {
        return o.filePath
    })
    shareImgContent('这是标题', content, pictures)
        // shareHref(msg);

}
//分享相关结束

function checkRepeat(obj, type) { //验证是否重复
    var url = ''
    var msg = ''
    switch (type) {
        case 'lessonName':
            url = '/lesson/checkLessonName'
            msg = '课程名称已存在,请输入其他名称!'
            break;
        default:
            url = '/userInfo/checkPhone'
            msg = '电话号码已存在,请输入其他号码!'
            break;
    }
    var params = {};
    var index = '';
    if (type == 'lessonName') {
        index = 'lessonName'
    } else {
        index = 'phone'
    }
    params[index] = obj[type];
    apiAxios('POST', url, params, (data) => {
        if (data.info) {
            MessageBox('提示', msg);
            obj[type] = ''
        }
    })


}
export default {
    get: function(url, params, success, failure) {
        return apiAxios('GET', url, params, success, failure)
    },
    post: function(url, params, success, failure, img) {
        return apiAxios('POST', url, params, success, failure, img)
    },
    put: function(url, params, success, failure) {
        return apiAxios('PUT', url, params, success, failure)
    },
    delete: function(url, params, success, failure) {
        return apiAxios('DELETE', url, params, success, failure)
    },
    formatterImg,
    showImgDetail,
    tell,
    getImage,
    formatDate,
    formatTime,
    BackTop,
    goBack,
    createUpload,
    removeCookie,
    clearItem,
    payMoney,
    Golbale,
    share,
    clickModel,
    checkRepeat,
    utf16toEntities,
    updata
}